package io.renren.common.websocket;

import com.alibaba.fastjson.JSON;
import io.renren.common.utils.MapEntityUtil;
import io.renren.common.utils.sftp.FileProgressMonitor;
import io.renren.common.utils.sftp.FileSingLeTon;
import io.renren.common.utils.sftp.ScheduleSingLeTon;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.Session;
import java.util.Map;

public class SocketHeartbeat implements Runnable {

    private Logger logger = LoggerFactory.getLogger(SocketHeartbeat.class);

    private Session session;

    private Long userId;

    private FileProgressMonitor fileMonitor;

    public SocketHeartbeat(Session session) {
        super();
        this.session = session;
    }

    public SocketHeartbeat(Long userId,FileProgressMonitor fileMonitor) {
        super();
        this.userId = userId;
        this.fileMonitor = fileMonitor;
    }

    public SocketHeartbeat() {
        super();
    }

    public FileSingLeTon getFileTonInstance() {
        return (FileSingLeTon) ScheduleSingLeTon.getInsteans().getFileMap().get(this.fileMonitor.getUuid());
    }

    public void socketSendMsg() {
//        ScheduleSingLeTon scheduleSingLeTon = ScheduleSingLeTon.getInsteans();
//        Map<String,Object> schMap = MapEntityUtil.entityToMap(scheduleSingLeTon);
//        MyWebSocketHandler.sendMessage(String.valueOf(this.userId),JSON.toJSONString(schMap));
        FileSingLeTon fileSingLeTon = getFileTonInstance();
        Map<String,Object> schMap = MapEntityUtil.entityToMap(fileSingLeTon);
        MyWebSocketHandler.sendMessage(String.valueOf(this.userId),JSON.toJSONString(schMap));
    }

    @Override
    public void run() {
        logger.info("服务端开启发送心跳模式");
        while(!fileMonitor.isEnd()) {
            try {
                this.socketSendMsg();
                Thread.sleep(1500);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
//        ScheduleSingLeTon scheduleSingLeTon = ScheduleSingLeTon.getInsteans();
//        scheduleSingLeTon.setEnd(true);
        FileSingLeTon fileSingLeTon = getFileTonInstance();
        this.socketSendMsg();
        logger.info(fileSingLeTon.getFileName() + "  文件上传完成！");
        // 移除文件进度监视
        ScheduleSingLeTon.getInsteans().getFileMap().remove(this.fileMonitor.getUuid());
    }

}
